<script setup lang="ts">
import { watch, ref, markRaw, onMounted, nextTick } from "vue";
import leftCompWrapper from "../common/leftCompWrapper.vue";
import * as echarts from "echarts";
import { cloneDeep } from "@pureadmin/utils";
import { convertStringToNumber, normalizeNumber } from "../../utils";
defineOptions({
  name: "VChartPie"
});
const echartRef = ref();
let echartInstance: echarts.ECharts;
const isCollapsed = ref(false);
const props = withDefaults(
  defineProps<{
    propValue?: {
      contentList: Array<any>;
      title?: string;
      innerLabel?: string;
      collapsed?: boolean;
      iconName?: string;
      option?: Record<string, any>;
    };
    element?: {
      style: {
        width?: number;
        height?: number;
        display?: string;
      };
    };
  }>(),
  {
    propValue: () => ({
      contentList: [],
      option: {},
      title: "",
      innerLabel: "",
      collapsed: false,
      iconName: "alert"
    }),
    element: () => ({ style: {} })
  }
);
onMounted(() => {
  echartInstance = markRaw(
    echarts.init(echartRef.value, undefined, {
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    })
  );
  renderChart(props.propValue.contentList as any);
});

function formatStr(str) {
  const len = str?.length;
  const seprateLen = 7;
  if (len <= seprateLen) return str;
  let newStr = "";
  //几个字换行大于几就可以了
  let l = Math.ceil(len / seprateLen); //有些不能整除，会有余数，向上取整
  for (let i = 1; i <= l; i++) {
    //循环
    if (i < l) {
      //最后一段字符不能有\n
      newStr += str.slice(i * seprateLen - seprateLen, i * seprateLen) + "\n"; //字符串拼接
    } else if (i === l) {
      //最后一段字符不一定够9个
      newStr = newStr + str.slice((l - 1) * seprateLen, len); //最后的拼接在最后
    }
  }
  return newStr;
}
function renderChart(newVal = []) {
  try {
    let option = cloneDeep(props.propValue.option);
    /**
     * 1  正常
     * 2  停机
     * 3  异常
     * 4  离线
     * 11 隔离
     */
    let color = {
      "1": "#10B981",
      "2": "#EF4444",
      "3": "#F59E0B",
      "4": "#909399",
      "11": "#EF4444"
    };
    let data;
    if (newVal && Array.isArray(newVal)) {
      data = newVal.map(item => {
        const { label, value, status } = item;
        let itemStyle = { color: color[status] };
        return { name: label, itemStyle, value: normalizeNumber(value) };
      });
      const total = data.reduce((acc, item) => acc + normalizeNumber(item.value), 0);
      option.series[0].data = data;
      let textStyle = {
        fontSize: 12,
        backgroundColor: "transparent",
        rich: {
          o: {
            width: 70,
            color: "#000000",
            fontSize: 12
          },
          t: {
            width: 50,
            color: "#333",
            fontSize: 12,
            fontWeight: "bolder"
          }
        }
      };
      option.legend.textStyle = textStyle;
      option.legend.formatter = name => {
        let single = newVal.find(item => item.label === name);
        const tip = formatStr(name);
        return `{o|${tip}}    {t|${convertStringToNumber(single.value)}${single.unit ? single.unit : ""}}`;
      };
      option.series[0].tooltip.formatter = function (params) {
        // 获取当前项的颜色
        const colorSpan = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>`;
        // 计算百分比
        const percent = params.percent.toFixed(2);
        return `${colorSpan}${params.name}:&nbsp;&nbsp; &nbsp; ${percent}%`;
      };

      option.series[0].label.formatter = () => {
        const str = formatStr(props.propValue.innerLabel);
        return `{a|${convertStringToNumber(total)}}\n{b|${str || ""}}`;
      };
      option.series[0].label.rich = {
        a: { fontWeight: 700 }
      };
    }
    // 设置参数

    // 更新大小
    if (echartInstance && echartInstance.resize) {
      echartInstance.resize({
        width: props.element!.style!.width! - 47,
        height: props.element.style.height! > 240 ? props.element.style.height! - 63 : 240 - 63
      });

      // 配置参数
      nextTick(() => {
        echartInstance.setOption(option);
      });
    }
  } catch (e) {
    console.error(e);
  }
}

//用于编辑器参数改变时响应变化
watch(
  () => props.element,
  newVal => {
    //console.log(newVal);
    renderChart(props.propValue.contentList);
  },
  { deep: true, immediate: true }
);
watch(
  () => props.propValue.contentList,
  newVal => {
    renderChart(newVal as any);
  }
);
</script>

<template>
  <leftCompWrapper v-model="isCollapsed" :title="propValue.title" :icon-name="propValue.iconName" :has-collapsed="propValue.collapsed">
    <div ref="echartRef" />
  </leftCompWrapper>
</template>

<!-- <style lang="scss" scoped></style> -->
